package com.woniuxy.dr_mall.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.dr_mall.entity.MyResponseEntity;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 自定义授权类
 *
 * @author 杨耀
 */
public class MyPermissionsAuthorizationFilter extends PermissionsAuthorizationFilter {
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        String token = req.getHeader("token");
        String isAjax = req.getHeader("X-Requested-With");
        if (isAjax == null && token == null) {
            return super.onAccessDenied(request, response);
        }
        MyResponseEntity<Void> responseEntity = new MyResponseEntity<>();
        responseEntity.setCode(403);
        responseEntity.setMsg("无权限");
        ObjectMapper objectMapper = new ObjectMapper();
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(objectMapper.writeValueAsString(responseEntity));
        response.getWriter().flush();
        return false;
    }
}
